package com.bpf.base.controller.system;

import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bpf.base.bean.system.Role2MenuKeyForm;
import com.bpf.base.bean.system.TSysRoleForm;
import com.bpf.base.bean.system.TSysUserForm;
import com.bpf.base.common.Constants;
import com.bpf.base.controller.BaseController;
import com.bpf.base.model.system.Role2MenuExample;
import com.bpf.base.model.system.Role2MenuKey;
import com.bpf.base.model.system.TSysRole;
import com.bpf.base.service.system.Role2MenuService;
import com.bpf.base.service.system.TSysMenuService;
import com.bpf.base.service.system.TSysRoleService;
import com.bpf.base.service.system.TSysUserService;
import com.bpf.base.util.AjaxUtils;
import com.bpf.base.util.ExcelUitl;
import com.bpf.base.util.MapUtil;

/**
 * @date 2016-07-19 05:31:26
 */
@Controller
@RequestMapping(value = {"/system/role"})
public class TSysRoleController extends BaseController{
	private Logger logger = LoggerFactory.getLogger(TSysRoleController.class);

    @Resource
	private TSysRoleService tSysRoleService;
    
    @Autowired
	private Role2MenuService role2MenuService;
	

	@Autowired
	private TSysUserService userService;
	
	@Autowired
	private TSysMenuService tSysMenuService;
	
	
    @RequestMapping(value = { "/init", "" })
	public String init() {
		return "system/role";
	}

    /**
	 * 根据条件查询
	 * @param params
	 * @return
	 * @throws JSONException
	 */
	@RequestMapping("/getTSysRoleList")
	@ResponseBody
	public Map<String, Object> getTSysRoleList(HttpServletRequest request, TSysRoleForm form,String jsonpCallback){
		Integer pageNum = Integer.parseInt(null == request.getParameter("page") ? 1 + "" : request.getParameter("page").toString());
		Integer pageSize = Integer.parseInt(null == request.getParameter("rows") ? 10 + "" : request.getParameter("rows").toString());
		Map<String, Object> params = new HashMap<String, Object>();
		params = MapUtil.toMap(form);
		params.put("offset", (pageNum-1)*pageSize);
		params.put("limit", pageSize);
		return tSysRoleService.getTSysRoleList(params);
	}    
  
  	@RequestMapping("/addTSysRole")
	@ResponseBody
	public Map<String, Object> addTSysRole(HttpServletRequest request, TSysRole form,String jsonpCallback) throws UnsupportedEncodingException{
		Map<String, Object> params = new HashMap<String, Object>();
		// 参数检查
		params = MapUtil.toMap(form);
		// 调用service
		tSysRoleService.addTSysRole(params);
		return AjaxUtils.reponseToJson("添加", true);
	}
	
	/**
	 * 更新
	 * @param params
	 * @return
	 * @throws IllegalAccessException 
	 * @throws InstantiationException 
	 * @throws JSONException
	 */
	@RequestMapping("/updateTSysRole")
	@ResponseBody
	public Map<String, Object> updateTSysRole( TSysRole form,String jsonpCallback) throws InstantiationException, IllegalAccessException{
		// 参数检查
		TSysRole tSysRole = MapUtil.toObject(TSysRole.class, MapUtil.toMap(form));
		// 调用service
		tSysRoleService.updateTSysRole(tSysRole);
		return AjaxUtils.reponseToJson("修改", true);
	}
	
	/**
	 * 删除
	 * @param params
	 * @return
	 * @throws IllegalAccessException 
	 * @throws InstantiationException 
	 * @throws JSONException
	 */
	@RequestMapping("/deleteTSysRole")
	@ResponseBody
	public Map<String, Object> deleteTSysRole(HttpServletRequest request,String jsonpCallback) throws InstantiationException, IllegalAccessException{
		String[] idArray=request.getParameterValues("idArray[]");
		// 调用service
		if(tSysRoleService.delTSysRoleBat(idArray) > 0){
			return AjaxUtils.reponseToJson("删除", true);
		}else{
			return AjaxUtils.reponseToJson("删除", false);
		}
	}
	
	@RequestMapping("/exporttSysRole")
	public void exportTSysRole(HttpServletRequest request, HttpServletResponse response) throws Exception {
		response.setContentType("application/vnd.ms-excel;charset=utf-8");
		OutputStream out = response.getOutputStream();
		String title = "业主信息";
		String[] headers = { "住户编号", "业主姓名", "房产证", "土地证", "性别", "身份证", "联系电话" };
		String[] columns = { "id", "name", "housePropertyCert", "landCert", "gender", "idNo", "mobile" };
		List<TSysRole> houseList = tSysRoleService.getAllTSysRole(null);
		ExcelUitl<TSysRole> excelUtil = new ExcelUitl<TSysRole>();
		String pattern = "yyyy-MM-dd HH:mm:dd";
		response.setHeader("Content-Disposition", "attachment;filename=" + new String((title + ".xls").getBytes(), "iso-8859-1"));
		excelUtil.exportoExcel(title, headers, columns, houseList, out, pattern);
	}
	
	@RequestMapping(value = "/list")
	@ResponseBody
	public Map<String, Object> list(HttpServletRequest request, TSysRoleForm roleSearch) {
		Integer pageNum = Integer.parseInt(null == request.getParameter("page") ? 1 + "" : request.getParameter("page").toString());
		Integer pageSize = Integer.parseInt(null == request.getParameter("rows") ? 10 + "" : request.getParameter("rows").toString());
		Map<String, Object> conditions = new HashMap<String, Object>();
		conditions.put(Constants.Page.OFFSET, (pageNum - 1) * pageSize);
		conditions.put(Constants.Page.LIMIT, pageSize);
		conditions.put(Constants.Condition.ORDERBY_CLAUSE, "ROLE_ID DESC");

		return tSysRoleService.getTSysRoleList(conditions);
	}

	@ResponseBody
	@RequestMapping(value = "/getAll")
	public List<Map<String, String>> getAll() {
		return tSysRoleService.selectIdText();
	}

	@RequestMapping(value = "/save")
	@ResponseBody
	public Map<String, Object> save(TSysRole role) {
		if (tSysRoleService.addTSysRole(MapUtil.toMap(role)) > 0) {
			return AjaxUtils.reponseToJson(Constants.Action.SAVE, true);
		}
		return AjaxUtils.reponseToJson(Constants.Action.SAVE, false);
	}

	@ResponseBody
	@RequestMapping(value = "/edit/{id}")
	public TSysRole edit(@PathVariable(value = "id") Integer id) {
		TSysRoleForm form=new TSysRoleForm();
		form.setRoleId(id);
		return tSysRoleService.getAllTSysRole(MapUtil.toMap(form)).get(0);
	}

	@ResponseBody
	@RequestMapping(value = "/update")
	public Map<String, Object> update(TSysRole role) {
		if (tSysRoleService.updateTSysRole(role) > 0) {
			return AjaxUtils.reponseToJson(Constants.Action.UPDATE, true);
		}
		return AjaxUtils.reponseToJson(Constants.Action.UPDATE, false);

	}

	// 删除判断角色是否被用户关联
	@ResponseBody
	@RequestMapping(value = "/checkBind")
	public Boolean check(Integer roleId) {
		TSysUserForm form = new TSysUserForm();
		form.setRoleId(roleId);
		return userService.getAllTSysUser(MapUtil.toMap(form)).isEmpty();
	}

	@RequestMapping(value = "/deleteAll")
	@ResponseBody
	public Map<String, Object> delete(@RequestParam(value = "ids", required = true) Integer roleId) {
		TSysUserForm form = new TSysUserForm();
		form.setRoleId(roleId);
		if (tSysRoleService.delTSysRole(MapUtil.toMap(form)) > 0) {
			// 删除角色关联的菜单信息
			Role2MenuExample role2MenuExample = new Role2MenuExample();
			role2MenuExample.createCriteria().andRoleIdEqualTo(roleId);
			role2MenuService.deleteByExample(role2MenuExample);
			return AjaxUtils.reponseToJson(Constants.Action.DELETE, true);
		}
		return AjaxUtils.reponseToJson(Constants.Action.DELETE, false);

	}

	// 保存绑定菜单
	@ResponseBody
	@RequestMapping(value = "/saveBindMenu")
	public Map<String, Object> saveBindMenu(Integer roleId, String menuIds) {
		// 先删除
		Role2MenuExample role2MenuExample = new Role2MenuExample();
		role2MenuExample.createCriteria().andRoleIdEqualTo(roleId);
		role2MenuService.deleteByExample(role2MenuExample);
		// 后添加
		if (!StringUtils.isEmpty(menuIds)) {
			String[] StringArr = menuIds.split(",");
			Integer idArr[] = new Integer[StringArr.length];
			List<Role2MenuKey> role2MenuKeys = new ArrayList<Role2MenuKey>();
			Role2MenuKey role2MenuKey;
			for (int i = 0; i < StringArr.length; i++) {
				// 剔除掉id为1的-根节点
				if (!StringArr[i].equals("1")) {
					role2MenuKey = new Role2MenuKey();
					role2MenuKey.setMenuId(Integer.parseInt(StringArr[i]));
					role2MenuKey.setRoleId(roleId);
					role2MenuKeys.add(role2MenuKey);
				}
			}
			role2MenuService.insertBatch(role2MenuKeys);
		}
		return AjaxUtils.reponseToJson(Constants.Action.BIND, true);
	}

	@ResponseBody
	@RequestMapping(value = "/eidtBindMnt")
	public Map<String, Object> eidtBindMnt() {
		return AjaxUtils.reponseToJson(Constants.Action.BIND, true);
	}
	
}
